﻿using Microsoft.Xna.Framework;
using System;
using Terraria;
using Terraria.Audio;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;

namespace HardcoreGame.Common.Players
{
    public class ImpactPlayer : ModPlayer
    {
        public override void PreUpdateMovement()
        {
            Vector2 velocity = Player.velocity;
            float speed = velocity.Length();
            if (speed >= 10)
            {
                CheckWallCollision(velocity, speed);
            }
        }

        private void CheckWallCollision(Vector2 velocity, float speed)
        {
            int tileX, tileY;
            Tile tile;
            if (Math.Abs(velocity.X) > 0.1f)
            {
                tileX = (int)((Player.position.X + (velocity.X > 0 ? Player.width : 0)) / 16) + (velocity.X > 0 ? 1 : -1);
                tileY = (int)(Player.position.Y / 16);
                for (int y = tileY; y < tileY + Player.height / 16 + 1; y++)
                {
                    tile = Framing.GetTileSafely(tileX, y);
                    if (tile.HasTile && Main.tileSolid[tile.TileType] && !Main.tileSolidTop[tile.TileType])
                    {
                        int baseDamage = (int)(speed * 6f);
                        Player.statLife = Math.Max(0, Player.statLife - baseDamage);
                        SoundEngine.PlaySound(SoundID.PlayerHit, Player.position);
                        CombatText.NewText(Player.Hitbox, Color.Orange, baseDamage);
                        if (Player.statLife <= 0)
                        {
                            #pragma warning disable CS0618
                            Player.KillMe(PlayerDeathReason.ByCustomReason($"{Player.name}" + Language.GetTextValue("Mods.HardcoreGame.Tips.7")), 0, 0, false);
                            #pragma warning restore CS0618
                        }
                        return;
                    }
                }
            }
        }
    }
}